package com.zjs.jsp.mongodbapi.web;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

/**
 * @author 李文
 * @create 2017-09-18 9:12
 **/
@RestController
public class PathPlanningController
{

    // 以下为 获得 两点之间最短距离
    //定义 地球半径
    private static final BigDecimal EARTH_RADIUS = new BigDecimal(6378.137);
    //定义Math.PI
    private static final BigDecimal MATH_PI = new BigDecimal(Math.PI);

    /**
     * 计算弧长
     **/
    private BigDecimal getRed(BigDecimal big) {
        return big.multiply(MATH_PI).divide(new BigDecimal(180.0), BigDecimal.ROUND_DOWN);
    }

    /**
     * 计算 两点 之间  的 最短距离
     *
     * @return 返回 数据 为 两点之间的 米数
     */
    @GetMapping("/path/{lat1}/{lng1}/{lat2}/{lng2}")
    @ApiOperation(value = "经纬度直线距离", notes = "经纬度直线距离")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "lat1", required = true, dataType = "BigDecimal", paramType = "query"),
            @ApiImplicitParam(name = "lng1", required = true, dataType = "BigDecimal", paramType = "query"),
            @ApiImplicitParam(name = "lat2", required = true, dataType = "BigDecimal", paramType = "query"),
            @ApiImplicitParam(name = "lng2", required = true, dataType = "BigDecimal", paramType = "query"),
    })
    public BigDecimal getShortestDistance(@RequestParam BigDecimal lat1, @RequestParam BigDecimal lng1,
                                          @RequestParam BigDecimal lat2, @RequestParam BigDecimal lng2) {

        try {

            BigDecimal radLat1 = getRed(lat1);
            BigDecimal radLat2 = getRed(lat2);
            BigDecimal a = radLat1.subtract(radLat2);
            BigDecimal b = getRed(lng1).subtract(getRed(lng2));

            Double sinA = Math.sin(a.doubleValue() / 2);
            Double sinB = Math.sin(b.doubleValue() / 2);
            Double cosA = radLat1.doubleValue();
            Double cosB = radLat2.doubleValue();
            Double obj = 2 * Math.asin(Math.sqrt(Math.pow(sinA, 2) + Math.cos(cosA) * Math.cos(cosB) * Math.pow(sinB, 2)));
            BigDecimal s = new BigDecimal(obj);
            s = s.multiply(EARTH_RADIUS);
            return format(s, 3);
        } catch (Exception e) {
            return new BigDecimal(10000000);
        }
    }

    private BigDecimal format(BigDecimal big, int scale) {
        scale = 0 > scale ? 0 : scale;
        big = big.setScale(scale, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(1000));
        return big;
    }
}
